package dao

import (
	"context"
	"gorm.io/gorm"
	"mall_2.0/respository/db/model"
	"mall_2.0/types"
)

type AddressDao struct {
	*gorm.DB
}

func NewAddressDao(ctx context.Context) *AddressDao {
	return &AddressDao{
		NewDBClient(ctx),
	}
}

func NewAddressDaoByDB(db *gorm.DB) *AddressDao {
	return &AddressDao{db}
}

// CreateAddress 创建地址
func (dao *AddressDao) CreateAddress(address *model.Address) error {
	return dao.DB.Model(&model.Address{}).Create(&address).Error
}

// DeleteAddress 删除地址
func (dao *AddressDao) DeleteAddress(aID, uID uint) error {
	return dao.DB.Model(&model.Address{}).Where("id = ? AND user_id = ?", aID, uID).Delete(&model.Address{}).Error
}

// UpdateAddress 修改地址
func (dao *AddressDao) UpdateAddress(aID uint, address *model.Address) error {
	return dao.DB.Model(&model.Address{}).Where("id = ?", aID).Updates(&address).Error
}

// GetAddressByAID 根据地址ID获取地址
func (dao *AddressDao) GetAddressByAID(aID, uID uint) (address *model.Address, err error) {
	err = dao.DB.Model(&model.Address{}).Where("id = ? AND user_id = ?", aID, uID).First(&address).Error
	return
}

// ListAddressByUID 根据用户ID获取用户所有地址
func (dao *AddressDao) ListAddressByUID(uID uint) (addresses []*types.AddressResp, err error) {
	err = dao.DB.Model(&model.Address{}).Where("user_id = ?", uID).Order("create_at desc").
		Select("id, user_id, name, phone, address, UNIX_TIMESTAMP(create_at)").
		Find(&addresses).Error
	return
}
